package com.genersoft.iot.vmp.interceptor;

import com.genersoft.iot.vmp.utils.DateUtil;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.Statement;
import java.util.Properties;

/**
 * @Description
 * @Author HDaQ
 * @Date 2024/9/10 17:30
 */
@Intercepts({@Signature(type = StatementHandler.class, method = "update", args = {Statement.class})
        , @Signature(type = StatementHandler.class, method = "batch", args = {Statement.class})
        , @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})
})
public class SqlInterceptor implements Interceptor {

    private final Logger logger = LoggerFactory.getLogger(SqlInterceptor.class);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 获取目标类的实例，即StatementHandler
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();

        // 在这里你可以获取到要执行的SQL语句
        String sql = statementHandler.getBoundSql().getSql();
        if (sql.contains("now()")) {
            String now = "'"+DateUtil.getNow()+"'";
            sql = sql.replaceAll("now\\(", now + "_").replaceAll("_\\)", "");
            logger.info("替换后的SQL语句为：{}", sql);
            BoundSql boundSql = statementHandler.getBoundSql();
            Field sqlFiled = boundSql.getClass().getDeclaredField("sql");
            sqlFiled.setAccessible(true);
            sqlFiled.set(boundSql, sql);
        }

        // 继续执行原有的方法
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        // 当目标类是StatementHandler类型时，返回代理对象
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // 可以用来设置拦截器属性
    }
}
